import { NotFoundItem, Success } from "../../code/http-exception";
import auth from "../../middlewares/auth"
import { sequelize } from "../../sql/db";
import CouponEncrypt from "../../sql/module/coupon/coupon_encrypt";
import Coupon from "../../sql/module/coupon/index";
import { InfoValidator, ListValidator } from "../../validators/public";
import { Md5 } from "ts-md5";

const router: Api = new Map()
/**
 * 获取邀请码
 * @returns userCode
 */
router.set('/couponEncrypt', [auth('public'), async (ctx) => {
    const UserId = ctx.auth.id
    const md5 = new Md5()
    md5.appendStr(Math.random() + '')
    const code = md5.end()?.slice(0, 10)
    const [encrypt, created] = await CouponEncrypt.findOrCreate({ where: { UserId }, defaults: { UserId, code } })
    if (!created) await encrypt.update({ code })
    throw new Success(encrypt.dataValues.code)
}])
/**
 * 添加优惠券
 * @param code string
 * @returns ok
 */
router.set('/addCouponByUser', [auth('public'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const md5 = new Md5()
    md5.appendStr(Math.random() + '')
    const couponCode = md5.end()
    const code = v.get('query.id')
    const encrypt = await CouponEncrypt.findOne({ where: { code } })
    if (!encrypt) { throw new NotFoundItem('邀请码不存在') }
    if (await Coupon.findOne({ where: { UserId, from: 'otherUser' } })) { throw new NotFoundItem('已领取过新人邀请码') }
    await Coupon.create({
        UserId, name: '新人邀请', price: 20, code: couponCode,
        lowPrice: 200,
        from: 'otherUser', fromBy: encrypt.dataValues.UserId
    })
    throw new Success()
}])
/**
 * 优惠券列表
 * @param limit number
 * @param page_index number
 * @returns { list, total }
 */
router.set('/couponList', [auth('public'), async (ctx) => {
    const v = await new ListValidator().validate(ctx)
    await sequelize.sync()
    const UserId = ctx.auth.id
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const { rows, count } = await Coupon.findAndCountAll({
        where: { UserId, state: 0 },
        limit: limit * 1,
        offset: (page_index - 1) * limit
    })
    throw new Success({ list: rows, total: count })
}])
/**
 * 轮查核销状态
 * @param code string
 * @returns ok
 */
router.set('/couponState', [auth('public'), async (ctx) => {
    const v = await new InfoValidator().validate(ctx)
    const code = v.get('query.id')
    const coupon = await Coupon.findOne({
        where: {
            code, state: 0
        }
    })
    if (!coupon) { throw new Success('success') }
    throw new Success()
}])
/**
 * 核销优惠券
 * @param code string
 * @returns ok
 */
router.set('/verification', [auth('public'), async (ctx) => {
    const v = await new InfoValidator().validate(ctx)
    const code = v.get('query.id')
    const StoreItemId = v.get('query.StoreItemId')
    const coupon = await Coupon.findOne({
        where: {
            code, state: 0
        }
    })
    if (!coupon) { throw new NotFoundItem('未发现优惠券') }
    await coupon.update({ state: 1, StoreItemId })
    throw new Success()
}])

/**
 * 历史优惠券
 * @param limit number
 * @param page_index number
 * @returns { list, total }
 */
router.set('/historyList', [auth('public'), async (ctx) => {
    const v = await new ListValidator().validate(ctx)
    await sequelize.sync()
    const UserId = ctx.auth.id
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const { rows, count } = await Coupon.findAndCountAll({
        where: { UserId, state: 1 },
        limit: limit * 1,
        offset: (page_index - 1) * limit
    })
    throw new Success({ list: rows, total: count })
}])
export { router }